package site.teamo.biu.net.server.core.http_https_proxy.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import site.teamo.biu.net.common.constant.ChannelAttributeKey;
import site.teamo.biu.net.common.handler.ExceptionHandler;
import site.teamo.biu.net.common.handler.SimpleTransferHandler;
import site.teamo.biu.net.common.http_https_proxy.ChannelGroups;
import site.teamo.biu.net.common.message.connect_to_destination_address.ConnectToDestinationAddressResponse;
import site.teamo.biu.net.common.util.HostPort;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author haocongshun
 * @date 2023/06/09 10:00:54
 */
@Slf4j
public class DirectTransferClient {

    private EventLoopGroup group;

    private final Bootstrap bootstrap;

    private final ChannelGroups channelGroups;

    //入流量
    private final AtomicLong in;
    //出流量
    private final AtomicLong out;

    public DirectTransferClient(AtomicLong in, AtomicLong out) {
        this.in = in;
        this.out = out;
        this.group = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new Initializer());
        this.channelGroups = new ChannelGroups();
    }

    public void direct(HostPort hostPort, Channel channelFromProxyClient) {
        try {
            Channel channelToDestination = this.bootstrap.connect(hostPort.host(), hostPort.port()).sync().channel();
            log.info("使用[{}]协议与目标{}:{}地址的连接已建立", hostPort.protocol(), hostPort.host(), hostPort.port());
            //先将与自代理客户端连接的channel和与目的地连接的channel进行属性绑定
            channelToDestination.attr(ChannelAttributeKey.TARGET_CHANNEL).setIfAbsent(channelFromProxyClient);
            channelFromProxyClient.attr(ChannelAttributeKey.TARGET_CHANNEL).setIfAbsent(channelToDestination);
            //给与代理客户端连接的channel添加一个转发Handler
            channelFromProxyClient.pipeline().addBefore("exception", "simple-transfer", new SimpleTransferHandler("代理客户端数据向目的地转发", out));
            //向代理客户发送与目标已建立连接的消息
            channelFromProxyClient.writeAndFlush(new ConnectToDestinationAddressResponse(
                    hostPort.host(),
                    hostPort.port(),
                    true
            )).addListener(future -> {
                if (future.isSuccess()) {
                    //消息发送成功后，将与代理客户端连接的channel的编码器和解码器移除掉
                    channelFromProxyClient.pipeline().remove("message-decoder");
                    channelFromProxyClient.pipeline().remove("message-encoder");
                    channelGroups.put(hostPort, channelToDestination);
                    log.info("代理通道[{}]{}:{}已建立", hostPort.protocol(), hostPort.host(), hostPort.port());
                    channelFromProxyClient.attr(ChannelAttributeKey.DESTINATION_INFO).setIfAbsent(hostPort);
                    channelToDestination.attr(ChannelAttributeKey.DESTINATION_INFO).setIfAbsent(hostPort);
                } else {
                    channelToDestination.close();
                    channelFromProxyClient.close();
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void close() {
        channelGroups.close();
        this.group.shutdownGracefully();
    }

    private class Initializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast("simple-transfer", new SimpleTransferHandler("将目的地响应转发给浏览器", in))
                    .addLast("idle", new IdleStateHandler(0, 0, 30, TimeUnit.SECONDS))
                    .addLast("exception", new ExceptionHandler());
        }
    }
}
